package com.leshowski.agendaUCV2.facebook.control;

import java.util.List;

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.types.Account;
import com.restfb.types.FacebookType;

public class ManejaFacebook {
	
	String accesToken    = null;
	String dondePublicar = null;
	
	public ManejaFacebook(String accesToken,
						  String dondePublicar){
		
		this.accesToken = accesToken;
		this.dondePublicar = dondePublicar;
		
	}
	
	public void publicaFacebook(String horario,
								String urlFoto,
								String link,
								String titulo,
								String caption){
	
		String accesTokenRecursoSolic = "";
		
		//Crea la instancia facebook
		FacebookClient facebookClient = new DefaultFacebookClient(this.accesToken);
		
		Connection<Account> myAccounts;
		myAccounts = facebookClient.fetchConnection("me/accounts", Account.class);
		
		List<Account> datos =  myAccounts.getData();
			
		for(Account accTemp:datos){
			if(accTemp.getName().equals(this.dondePublicar)){
				accesTokenRecursoSolic = accTemp.getAccessToken();
				break;
			}
		}
		
		facebookClient = new DefaultFacebookClient(accesTokenRecursoSolic);
		
		if(urlFoto == null || urlFoto.equals(""))
			facebookClient.publish("me/feed", FacebookType.class, 
							   	   Parameter.with("message", horario),
							   	   Parameter.with("link",link),
							   	   Parameter.with("name",titulo),
							   	   Parameter.with("caption",caption));
		else
			facebookClient.publish("me/feed", FacebookType.class, 
				   	   Parameter.with("message", horario),
				   	   Parameter.with("link",link),
				   	   Parameter.with("name",titulo),
				   	   Parameter.with("caption",caption),
				   	   Parameter.with("picture", urlFoto));
		
	}
}
